package com.example.security.assembly;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.base.entity.BaseEntity;
import com.example.security.config.PasswordEncoderConfig;
import com.example.sys.entity.SystemUser;
import com.example.sys.service.ISystemUserService;
import com.google.common.collect.Lists;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 用于用户加载
 * 自定义用户加载逻辑
 */
@Data
@Component
public class SystemUserDetailsService implements UserDetailsService {

    private ISystemUserService userService;

    @Autowired
    public SystemUserDetailsService(ISystemUserService userService){
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isBlank(username)){
            throw new UsernameNotFoundException("用户名为空");
        }
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getLoginName, username);
        SystemUser systemUser = userService.getOne(queryWrapper);
        if (Objects.isNull(systemUser)){
            throw new UsernameNotFoundException("用户不存在, 请注册用户");
        }
        boolean disabled = true;
        //如果用户被删除了 那么禁用用户
        if (systemUser.getDeleted() == BaseEntity.ONE){
            disabled = false;
        }
        //获取用户角色
        List<SimpleGrantedAuthority> roleList = Lists.newArrayList();

        //返回用户
        return User.builder()
                .username(username)
                .password(systemUser.getLoginPassword())
                //此处设置用户拥有的权限
                .authorities(roleList)
                .disabled(disabled).build();
    }

    /**
     * 密码验证
     * @param userDetails
     * @param password
     * @return
     */
    public boolean matches(UserDetails userDetails, String password){
        return PasswordEncoderConfig.passwordMatches(password, userDetails.getPassword());
    }
}
